#!/bin/bash

# 擎动智造自动化执行平台 - 启动脚本

echo "========================================"
echo "🚀 擎动智造自动化执行平台"
echo "========================================"
echo ""

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 检查Python是否安装
if ! command -v python3 &> /dev/null && ! command -v python &> /dev/null; then
    echo "❌ 错误: 未找到Python，请先安装Python 3.8+"
    exit 1
fi

# 使用python3或python
PYTHON_CMD="python3"
if ! command -v python3 &> /dev/null; then
    PYTHON_CMD="python"
fi

echo "📦 检查Python依赖..."
cd core/web
if [ ! -f "requirements.txt" ]; then
    echo "❌ 错误: 未找到 requirements.txt"
    exit 1
fi

# 检查是否需要安装依赖
$PYTHON_CMD -c "import fastapi" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "📥 安装Python依赖..."
    pip install -r requirements.txt
    if [ $? -ne 0 ]; then
        echo "❌ 依赖安装失败，请检查网络连接或手动安装"
        exit 1
    fi
fi

echo "✅ Python依赖检查完成"
echo ""

# 返回项目根目录
cd "$SCRIPT_DIR"

# 检查前端是否已构建
FRONTEND_DIST="$SCRIPT_DIR/ui/dist"
if [ ! -d "$FRONTEND_DIST" ] || [ ! -f "$FRONTEND_DIST/index.html" ]; then
    echo "⚠️  前端未构建，正在构建前端..."
    
    # 检查Node.js是否安装
    if ! command -v node &> /dev/null; then
        echo "❌ 错误: 未找到Node.js，请先安装Node.js 16+"
        echo "💡 提示: 可以手动构建前端: cd ui && npm install && npm run build"
        echo "⏩ 跳过前端构建，仅启动后端服务..."
    else
        cd "$SCRIPT_DIR/ui"
        
        # 检查是否需要安装依赖
        if [ ! -d "node_modules" ]; then
            echo "📥 安装前端依赖..."
            npm install
            if [ $? -ne 0 ]; then
                echo "❌ 前端依赖安装失败"
                echo "💡 提示: 可以手动安装: cd ui && npm install"
                echo "⏩ 跳过前端构建，仅启动后端服务..."
            fi
        fi
        
        # 构建前端
        if [ -d "node_modules" ]; then
            echo "🔨 构建前端..."
            npm run build
            if [ $? -eq 0 ]; then
                echo "✅ 前端构建完成"
            else
                echo "❌ 前端构建失败"
                echo "💡 提示: 可以手动构建: cd ui && npm run build"
                echo "⏩ 跳过前端，仅启动后端服务..."
            fi
        fi
        
        cd "$SCRIPT_DIR"
    fi
else
    echo "✅ 前端已构建"
fi
echo ""

# 返回到web目录
cd "$SCRIPT_DIR/core/web"

# 检查端口是否被占用
PORT=10001
if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "⚠️  警告: 端口 $PORT 已被占用"
    echo "正在尝试停止旧进程..."
    lsof -ti:$PORT | xargs kill -9 2>/dev/null
    sleep 2
fi

# 保存PID到文件
PID_FILE="$SCRIPT_DIR/.web_server.pid"

echo "🔧 启动后端服务..."
echo "📍 服务地址: http://localhost:$PORT"
echo "📚 API文档: http://localhost:$PORT/docs"
echo "🌐 前端页面: http://localhost:$PORT"
echo ""

# 启动后端服务（后台运行）
nohup $PYTHON_CMD main.py > "$SCRIPT_DIR/server.log" 2>&1 &
SERVER_PID=$!

# 保存PID
echo $SERVER_PID > "$PID_FILE"

echo "✅ 后端服务已启动 (PID: $SERVER_PID)"
echo "📝 日志文件: $SCRIPT_DIR/server.log"
echo ""

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 3

# 检查服务是否正常运行
if ps -p $SERVER_PID > /dev/null 2>&1; then
    # 检查服务是否响应
    for i in {1..10}; do
        if curl -s http://localhost:$PORT/health > /dev/null 2>&1; then
            echo "✅ 服务启动成功！"
            echo ""
            echo "========================================"
            echo "✨ 项目启动完成！"
            echo "========================================"
            echo ""
            echo "📌 访问地址:"
            echo "   前端页面: http://localhost:$PORT"
            echo "   API文档:  http://localhost:$PORT/docs"
            echo ""
            echo "🔐 测试账号:"
            echo "   用户名: admin"
            echo "   密码: admin123"
            echo ""
            echo "💡 提示:"
            echo "   - 查看日志: tail -f $SCRIPT_DIR/server.log"
            echo "   - 停止服务: ./stop.sh"
            echo ""
            
            # 自动打开浏览器
            echo "🌐 正在打开浏览器..."
            if command -v open &> /dev/null; then
                # macOS
                open "http://localhost:$PORT"
            elif command -v xdg-open &> /dev/null; then
                # Linux
                xdg-open "http://localhost:$PORT"
            elif command -v start &> /dev/null; then
                # Windows (Git Bash)
                start "http://localhost:$PORT"
            else
                echo "⚠️  无法自动打开浏览器，请手动访问: http://localhost:$PORT"
            fi
            
            exit 0
        fi
        echo "等待服务响应... ($i/10)"
        sleep 1
    done
    
    echo "⚠️  服务已启动但无响应，请检查日志: tail -f $SCRIPT_DIR/server.log"
    exit 1
else
    echo "❌ 服务启动失败，请检查日志: tail -f $SCRIPT_DIR/server.log"
    exit 1
fi
